package com.bianmin.coomen;

//阿里云OSS管理类
//主要负责图片以及其他文件上传

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.bianmin.Data.Result;
import com.bianmin.Data.ResultCode;
import org.springframework.web.multipart.MultipartFile;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;


public class AlyOssManager {

    private OSS ossClient;

    private String accessKeyId = "LTAI5tGkng1ebFBVNJwN1sky";
    private String accessKeySecret = "KDemuHM8c70KroZLYDYHVxe9pG4QWC";
    private String endpoint = "oss-cn-shanghai.aliyuncs.com";
    private String bucketName = "wfn53400";

    //创建OSS client 对象
    public OSS getOssClient() {
        if (ossClient == null) {
            ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        }
        return ossClient;
    }

    //上传文件的方法
    public Result<String> uploadFile(MultipartFile file )  {
        try {
            //讲流文件转换成inputStream
            InputStream inputStream = file.getInputStream();
            //设置文件名称
            String filename = Util.randomString(5) + String.valueOf(System.currentTimeMillis()) + ".png";
            //设置文件路径
            String filePath = "image/" + filename;
            //开始上传文件
            getOssClient().putObject(bucketName,filePath,inputStream);
            //关闭oss链接
            getOssClient().shutdown();
            //返回文件名称
            return Result.success(filename);
        } catch (FileNotFoundException e) {
            return Result.error(ResultCode.RC1002);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    //通过文件名删除文
    public void deleteFile(String filename) {
        //判断是否是华为OBS的地址，如果是就跳过，不处理，
        if (filename.contains("http")) {
            System.out.println("删除了华为的数据");
            return;
        }

        //下面是处理阿里云OSS的逻辑
        if (!filename.isEmpty()) {
           String[] fileNames = filename.split(",");
            for (String name : fileNames) {
                getOssClient().deleteObject(bucketName, "image/" + name);
            }
        }

    }

}
